/* Gauge - Performance Measurement Framework for Mobile Platforms
 * Copyright (C) 2013, Juha Hytonen <juha.a.hytonen@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.gauge.GaugeServer;

import java.io.File;
import java.util.logging.Logger;

/**
 * Provides access to command line arguments and/or their default values.
 */
public final class Arguments {
    
    private static final Logger log = Logger.getLogger("org.gauge.GaugeServer");

    private static final int DefaultPort = 9565;
    private static final String DefaultTargetDir = "";
    
    private static final String ArgPort = "-port";
    private static final String ArgTargetDir = "-target-dir";
    
    private static int port = DefaultPort;
    private static String targetDir = DefaultTargetDir;
    
    public static void Parse(String[] pArgs) {
        parseArguments(pArgs);
    }
       
    public static int GetPort() {
        return port;
    }
    
    public static String GetTargetDir() {
    	return targetDir;
    }

    private static void parseArguments(String[] args) {
        for(int i = 0; i < (args.length - 1); i++) {
            String name = args[i];
            String value = args[i+1];
            
            log.info("Parsing argument " + name);
            if(name.equals(ArgPort)) {
            	port = parseInt(value, DefaultPort);
            }
            else if(name.equals(ArgTargetDir)) {
            	targetDir = parseTargetDir(value);
            }
            else {
                log.warning("Unrecognized argument.");
            }
        }
    }
    
    private static int parseInt(String value, int defaultValue) {
        int intValue = defaultValue;
        try {
        	intValue = Integer.parseInt(value);
        }
        catch(NumberFormatException e) {
            log.warning("Invalid value supplied, falling back to default " + defaultValue);
        }
        return intValue;
    }
    
    private static String parseTargetDir(String dirName) {
    	File dir = new File(dirName);
    	if (dir.exists() && dir.isDirectory()) {
    		return dirName;
    	}
    	else {
            log.warning("Invalid directory supplied, falling back to default " + DefaultTargetDir);
            return DefaultTargetDir;
    	}
    }

}
